import axios from "axios";//进行axios二次封装，使用请求拦截和响应拦截
import { ElMessage } from 'element-plus';
import userStore from "../store/modules/user";
import { sessionStorage } from "./storage";
import { useRouter } from "vue-router";

//利用axios对象的create方法，去创建axios实例
const request = axios.create({
  baseURL: '/api',
  timeout: 50000, //
  headers: { 'Content-Type': 'application/json;charset=utf-8' },
})

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    if (!config.headers) {
      throw new Error(`Expected 'config' and 'config.headers' not to be undefined`);
    }
    const user  = userStore();
    if (user.token) {
      // config.headers.Authorization = `${sessionStorage.get('token')}`;
      config.headers.token = `${sessionStorage.get('token')}`;

    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  })

// 响应拦截器
request.interceptors.response.use(
  (response) => {
    const code = response.data.code || 200
    //对下载流进行处理
    if (response.request.responseType ===  'blob') {
      return response.data
    }
    const user  = userStore();
    const router = useRouter();
    if (code === 401) {
      user.resetToken();
      router.push("/login");
    } else if (response.data.code !== 200) {
      return ElMessage({
        message: response.data.msg,
        type: 'error',
      });
    } else {
      return response.data;
    }
  },
  (error) => {
    let message = ''
    let status = error.response.status;
    switch(status) {
      case 401:
        message = "token过期"
        break;
      case 403:
        message = "无权访问"
        break;
      default:
        message = "网路出现问题"
    }
    ElMessage({
      message,
      type: 'error',
    });
    return Promise.reject(error);
  }
);

export default request;